package com.server.ejb;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.server.entity.Account;
import com.server.entity.User;

import java.util.List;
/**
 * Session Bean implementation class UserBean
 */
@Stateless
@LocalBean
public class UserBean implements UserBeanLocal {

	@PersistenceContext
	private EntityManager em;
    /**
     * Default constructor. 
     */
    public UserBean() {
        // TODO Auto-generated constructor stub
    }
    
    
    public User GetUserById(String userId){
    	try{
    		em.getTransaction().begin();
    		Query query= em.createNamedQuery("GetUserByID");
    		query.setParameter("userId", userId);
    		User result= (User) query.getSingleResult();
    		em.getTransaction().commit();
    		return result;
    	}
    	catch(Exception e){
    		em.getTransaction().rollback();
    	}
    	finally{
    	}
    	return null;
    }
    
    public User GetUserByName(String userName){
    	try{
    		em.getTransaction().begin();
    		Query query= em.createNamedQuery("GetUserByName");
    		query.setParameter("userName", userName);
    		User result= (User) query.getSingleResult();
    		em.getTransaction().commit();
    		return result;
    	}
    	catch(Exception e){
    		em.getTransaction().rollback();
    	}
    	finally{
    	}
    	return null;
    }
    
    

	public boolean RegisterUser(User user, Account account){
					
    		Query query= em.createNamedQuery("GetUserByID");
    		query.setParameter("userId", user.getUserId());
    		
    		if(query.getResultList().isEmpty())
    		{
    			em.persist(user);
    			em.persist(account);
    			return true;
    		}
    		else
    		{
    			query = em.createNamedQuery("GetAccountByUser");
    			query.setParameter("userId", user.getUserId());
    			if(query.getResultList().isEmpty()){
    				em.persist(account);
    			}
    				
    			return true;
    		}
    }

}
